package com.qlk.vorder.manager.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.qlk.common.manager.BaseManager;
import com.qlk.common.utils.config.PropertiesHelper;
import com.qlk.common.utils.page.PageUtil;
import com.qlk.common.utils.serialize.JsonHelper;
import com.qlk.common.utils.wrap.WrapMapper;
import com.qlk.common.utils.wrap.Wrapper;
import com.qlk.vorder.dao.OrderLogDao;
import com.qlk.vorder.dao.OrdersDao;
import com.qlk.vorder.dao.SerialLogDao;
import com.qlk.vorder.dao.TaskDao;
import com.qlk.vorder.domain.OrderLog;
import com.qlk.vorder.domain.Orders;
import com.qlk.vorder.domain.Task;
import com.qlk.vorder.domain.enums.OrderStatusEnum;
import com.qlk.vorder.domain.enums.VorderTaskTypeEnum;
import com.qlk.vorder.domain.query.OrdersQuery;
import com.qlk.vorder.manager.OrdersManager;
import com.qlk.vorder.sdk.api.request.OrdersRequestDto;
import com.qlk.vorder.utils.exceptions.Constant;
import com.qlk.vorder.utils.exceptions.QueueIdGen;

/**
 * OrdersManager接口的实现类
 * 
 * @author zhaoyanan
 * @version 2016-7-28 14:14:00
 * 
 */
@Component
public class OrdersManagerImpl extends BaseManager implements OrdersManager {

	@Autowired
	private OrdersDao ordersDao;
	@Autowired
	private TaskDao taskDao;
	@Autowired
	private OrderLogDao orderLogDao;
	@Autowired
	private SerialLogDao serialLogDao;
	/** LOG */
	private static final Log LOG = LogFactory.getLog(OrdersManagerImpl.class);

	/**
	 * {@inheritDoc}
	 */
	public boolean insert(final List<Orders> ordersList) {
		boolean resultFlag = false;
		if (null != ordersList && ordersList.size() > 0) {
			for (Orders orders : ordersList) {
				resultFlag = ordersDao.insert(orders);
				if (!resultFlag) {
					throw new RuntimeException("批量新增表信息异常");
				}
			}
		}

		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean insert(Orders orders) {
		return ordersDao.insert(orders);
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean update(final Orders orders) {
		return ordersDao.update(orders);
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Orders> queryOrdersList(OrdersQuery queryBean) {
		return ordersDao.queryOrdersList(queryBean);
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Orders> queryOrdersListWithPage(OrdersQuery queryBean, PageUtil pageUtil) {
		if (null == queryBean) {
			queryBean = new OrdersQuery();
		}

		// 查询总数
		int totalItem = queryOrdersCount(queryBean);

		if (pageUtil == null) {
			pageUtil = new PageUtil();
		}
		pageUtil.setTotalRow(totalItem);
		pageUtil.init();

		if (totalItem > 0) {
			queryBean.setPageIndex(pageUtil.getCurPage());
			queryBean.setPageSize(pageUtil.getPageSize());
			// 调用Dao翻页方法
			return ordersDao.queryOrdersListWithPage(queryBean);
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public int queryOrdersCount(OrdersQuery queryBean) {
		return ordersDao.queryOrdersCount(queryBean);
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean delete(Orders orders) {
		return ordersDao.delete(orders);
	}

	/**
	 * {@inheritDoc}
	 */
	public Orders getOrdersById(Long id) {
		return ordersDao.getOrdersById(id);
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean delete(final Orders[] orderss) {
		boolean resultFlag = false;
		if (null != orderss && orderss.length > 0) {
			for (int i = 0; i < orderss.length; i++) {
				resultFlag = delete(orderss[i]);
				if (!resultFlag) {
					throw new RuntimeException("批量删除表信息异常!");
				}
			}
		}

		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	public Wrapper<?> insertOrderData(OrdersRequestDto request) {
		boolean flag = false;// 创建或更新订单状态
		boolean flagTask = false;// 创建任务状态
		boolean flagOrderLog = false;// 创建订单日志
		OrderLog orderLog = new OrderLog();
		OrdersQuery ordersQuery = new OrdersQuery();
		ordersQuery.setOrderid(request.getOrderid());
		Orders orders = ordersDao.getOrdersByOrderId(ordersQuery);
		Orders ordersInsert = convert(request);
		if (orders == null) {
			// 直接插入
			flag = ordersDao.insert(ordersInsert);
			if (!flag) {
				throw new RuntimeException("插入订单表失败!");
			}
			LOG.info("初始化虚拟订单数据flag:" + flag);
			orderLog.setOperateContent("初始化订单状态为:" + OrderStatusEnum.getName(request.getOrderStatus()));
		} else {
			// 更新订单数据：判断当前系统时间戳是否小于本次传入时间戳
			LOG.info("更新虚拟订单数据当前时间戳时间:" + orders.getTimestamp().getTime() + "本次传入时间戳:" + request.getTimestamp().getTime());
			if (orders.getTimestamp().getTime() > request.getTimestamp().getTime()) {
				return WrapMapper.wrap(Constant.ERROR_TIME, Constant.ERROR_TIME_TEXT);
			} else {
				// 更新数据
				orderLog.setOperateContent("订单状态:" + OrderStatusEnum.getName(orders.getOrderStatus()) + "变为:"
						+ OrderStatusEnum.getName(request.getOrderStatus()));
				flag = ordersDao.update(ordersInsert);
				if (!flag) {
					throw new RuntimeException("更新订单表失败!");
				}
				LOG.info("更新虚拟订单数据flag:" + flag);
				if (flag) {
					// 支付取消订单创建 退款任务
					LOG.info("支付已取消订单 订单状态:" + request.getOrderStatus() + "支付状态:" + request.getOrder().getPayStatus());
					if (request.getOrderStatus().equals(OrderStatusEnum.CANCEL.getType())) {
						if (request.getOrder().getPayStatus() != null && request.getOrder().getPayStatus().equals(Constant.Y)) {
							saveTask(request);
						} else if (request.getOrder().getPayStatus() == null && orders.getPayStatus().equals(Constant.Y)) {
							saveTask(request);
						}
					}
				}
			}
		}
		// 写订单日志
		orderLog.setOrderStatus(request.getOrderStatus());
		orderLog.setOrderid(request.getOrderid());
		orderLog.setCreateName("system");
		if (flag) {
			flagOrderLog = orderLogDao.insert(orderLog);
			if (!flagOrderLog) {
				throw new RuntimeException("写订单日志失败!");
			}
			LOG.info("创建虚拟订单成功flag:" + flag + "创建订单日志flagOrderLog:" + flagOrderLog);
			return WrapMapper.ok();
		}
		return WrapMapper.error();
	}

	private void saveTask(OrdersRequestDto request) {
		boolean flagTask;
		Task task = new Task();
		QueueIdGen queueIdGen = new QueueIdGen(Integer.valueOf(PropertiesHelper.newInstance().getValue("vorder.task.queue")));
		task.setKeyword1(request.getOrderid());
		task.setQueueId(queueIdGen.getQueueId());
		task.setOwnSign(PropertiesHelper.newInstance().getValue("vorder.task.sign"));
		task.setKeyword2(String.valueOf(VorderTaskTypeEnum.REFUND_SYSTEM_TYPE));
		task.setTaskType(String.valueOf(VorderTaskTypeEnum.REFUND_SYSTEM_TYPE.getType()));// VorderRefundTask
		flagTask = taskDao.insert(task);
		if (!flagTask) {
			throw new RuntimeException("创建任务失败!");
		}
		LOG.info("支付已取消订单创建退款单任务 flagTask:" + flagTask);
	}

	// 数据转换
	private Orders convert(OrdersRequestDto ordersDto) {
		LOG.info("创建虚拟订单 接入参数：" + JsonHelper.toJson(ordersDto));
		if (null == ordersDto) {
			return null;
		}
		Orders orders = new Orders();
		BeanUtils.copyProperties(ordersDto.getOrder(), orders);
		orders.setOrderid(ordersDto.getOrderid());
		orders.setOrderStatus(ordersDto.getOrderStatus());
		orders.setTimestamp(ordersDto.getTimestamp());
		orders.setUpdateName(Constant.SYSTEM_NAME);
		LOG.info("创建虚拟订单 转换数据：" + JsonHelper.toJson(orders));
		return orders;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean exist(Orders orders) {
		return ordersDao.exist(orders);
	}

	/**
	 * {@inheritDoc}
	 */
	public Orders getOrdersByOrderId(OrdersQuery ordersQuery) {
		return ordersDao.getOrdersByOrderId(ordersQuery);
	}

}
